<script setup lang="ts">

import {FormInst, FormItemRule, FormRules} from "naive-ui";
import {LoginReq} from "@/api/auth/types.ts";
import {authApi} from "@/api/auth";
import {uuid} from "@/utils";
import {useAppStore, useAuthStore} from "@/stores";
import {useRoute, useRouter} from "vue-router";

const authStore = useAuthStore();
const appStore = useAppStore();
const currentRoute = useRoute();
const router = useRouter();
const formRef = ref<FormInst | null>(null);
const formCaptchaImg = ref<string>()
const formLoginLoading = ref<boolean>(false)
const formData = reactive<LoginReq>(<LoginReq>{
  grant_type: 'password',
  uuid: uuid(),
  username: 'varianwrynn',
  password: '123456',
  captcha: '1'
});
const formRules = reactive<FormRules>({
  username: {
    required: true,
    validator: (rule: FormItemRule, value: string) => {
      if (!value) {
        return new Error('请输入用户名')
      }
      if (value.length < 5) {
        return new Error('用户名长度不能小于5')
      }
      return true
    },
    trigger: ['blur']
  },
  password: {
    required: true,
    validator: (rule: FormItemRule, value: string) => {
      if (!value) {
        return new Error('请输入密码')
      }
      if (value.length < 6) {
        return new Error('密码长度不能小于6')
      }
      return true
    },
    trigger: ['blur']
  }
})
onMounted(() => {
  handleClickCaptcha()
})
const handleClickCaptcha = () => {
  authApi.captcha({
    uuid: formData.uuid,
    width: 100,
    height: 38,
    darkTheme: appStore.darkTheme
  }).then((res) => {
    formCaptchaImg.value = res.data
  })
}
const handleClickToggleTheme = () => {
  appStore.toggleDarkTheme()
  handleClickCaptcha()
}
const handleClickLogin = () => {
  formLoginLoading.value = true
  const data = new FormData();
  data.append('grant_type', formData.grant_type)
  data.append('username', formData.username)
  data.append('password', formData.password)
  data.append('uuid', formData.uuid)
  data.append('captcha', formData.captcha)
  authApi.token(data).then(res => {
    window.$message?.success('登录成功')
    authStore.initToken(res.data)
    if (currentRoute.query.redirect) {
      router.push(currentRoute.query.redirect as string)
    } else {
      router.push('/')
    }
  }).finally(() => formLoginLoading.value = false)
}
</script>
<template>
  <n-flex class="login-page" h-full select-none>
    <n-card w400px m-a shadow>
      <template #header>
        <n-h1 text-center>
          Shalamayne Sword
          <n-icon @click="handleClickToggleTheme" cursor-pointer absolute top-12px right-12px>
            <icon-mdi:theme-light-dark/>
          </n-icon>
        </n-h1>
      </template>
      <n-form
          ref="formRef"
          :show-label="false"
          :model="formData"
          :rules="formRules"
          size="large"
      >
        <n-form-item label="用户名" path="username">
          <n-input v-model:value="formData.username" placeholder="用户名"/>
        </n-form-item>
        <n-form-item label="密码" path="password">
          <n-input v-model:value="formData.password" type="password" placeholder="密码"/>
        </n-form-item>
        <n-form-item label="验证码" path="captcha">
          <n-space>
            <n-input v-model:value="formData.captcha" placeholder="验证码" flex-1/>
            <n-tag v-if="formCaptchaImg" @click="handleClickCaptcha" ha cursor-pointer p0
                   :bordered="!appStore.darkTheme">
              <img :src="formCaptchaImg"/>
            </n-tag>
            <n-tag v-else h40px w100px cursor-pointer @click="handleClickCaptcha">
              <template #icon>
                <n-icon>
                  <icon-lucide:loader/>
                </n-icon>
                <span class="ml-8px">reload</span>
              </template>
            </n-tag>
          </n-space>
        </n-form-item>
        <n-form-item style="float: right">
          <n-button size="medium" type="primary" :loading="formLoginLoading" @click="handleClickLogin">登 录</n-button>
        </n-form-item>
      </n-form>
    </n-card>
  </n-flex>
</template>
<style scoped>
</style>
